/**
 * Created by ren on 10/04/2017.
 */
import React, {Component} from 'react';
import {
  StyleSheet,
  Platform,
  Image,
  Dimensions,
  StatusBar,
  TouchableWithoutFeedback,
  Linking,
  AlertIOS
}from 'react-native';
import {Container, Content, View, Text, List, ListItem, Left, Icon, Body, Right, Button, Badge} from 'native-base'
import {getSize} from '../utils/response'
import VFooter from '../components/Footer'
import PageUtil from '../utils/PageUtil'
import Information from './person/Information'
import Bank from './person/Bank'
import Services from './person/Services'
import * as api from '../utils/api'
import * as Netservice from '../utils/netservice'
import Login from '../views/Login'
import {connect} from 'react-redux'
import * as type from '../actions'
import appInfo from '../utils/appInfo'
import DialogAndroid from 'react-native-dialogs'
class Person extends Component {
  // 构造
  constructor(props) {
    super(props);
    this.PageUtil = new PageUtil();
    this.state = {
      phone: '',
      version: '',
      versionView: <Text note>1.0.0</Text>,
      address:'',
      options: {
        title: '版本更新',
        content: '新版本app又添加新功能了，快来体验吧！',
        positiveText: '确定',
        negativeText: '取消',
        onPositive: () => this._positive(),
      }
    }
  }

  componentDidMount() {
    this._getNowBus()
    this._getVersion()
  }

  /**
   * 拨打电话
   * @private
   */
  _positive() {
    Linking.canOpenURL(this.state.url).then(supported => {
      if (!supported) {
        console.log('Can\'t handle url: ' + this.state.url);
      } else {
        return Linking.openURL(this.state.url);
      }
    }).catch(err => console.error('An error occurred', err));
  }

  /**
   * 获取个人基本信息
   */
  _getNowBus() {
    const {dispatch}=this.props
    Netservice.get(api.getNowBus)
      .then(response => {
        dispatch(type.updateNickName(response.nickName ? response.nickName : ''))
        dispatch(type.updateSex(response.sex ? response.sex : ''))
        dispatch(type.updateBirthday(response.birthday ? response.birthday : ''))
        this.setState({
          phone: response.phone || '',
          address:'甘肃省'+response.cityPname+response.cityName,
          personData: response
        })
      })
  }

  /**
   * 检测app版本是否更新
   */
  _updateVersion() {
    if (this.state.version !== appInfo.version) {
      if (Platform.OS === 'ios') {
        AlertIOS.alert(
          '版本更新',
          '新版本app又添加新功能了，快来体验吧！',
          [
            {text: '取消'},
            {text: '确定', onPress: () => this._positive()},
          ]
        )
      } else {
        var dialog = new DialogAndroid();
        dialog.set(this.state.options);
        dialog.show();
      }
    }
  }

  /**
   * 获取app版本号
   */
  _getVersion() {
    Netservice.get(api.getVersion)
      .then(response => {
        if (response.version !== appInfo.version) {
          this.setState({
            version: response.version,
            url: response.url,
            versionView: <Badge style={{marginRight:0}}><Text>新</Text></Badge>
          })
        } else {
          this.setState({
            version: response.version,
            versionView: <Text note>{response.version}</Text>
          })
        }
      })
  }

  /**
   * 跳转到基本信息页面
   * @private
   */
  _toInformation() {
    this._getNowBus()
    this.PageUtil.jumpPageWithComponent(Information)
  }

  /**
   * 退出登录
   */
  _logOut() {
    const {dispatch}=this.props;
    Netservice.post(api.logOut).then(() => {
      storage.remove({
        key: 'loginState'
      });
      storage.load({
        key: 'loginData'
      }).then(ret => {
        let userName = ret.userName;
        storage.save({
          key: 'loginData',   // Note: Do not use underscore("_") in key!
          rawData: {
            userName: userName,
          }
        });
        dispatch(type.checkNotLogin())
        this.PageUtil.resetTo(Login)
      })
    })
  }

  render() {
    const {nickName}=this.props;
    return (
      <Container>
        <StatusBar
          backgroundColor={'#303135'}
        />
        <Content>
          <Image source={require('../images/person_background.png')} style={styles.personHead_img}>
            <View style={{flexDirection:'row',justifyContent:'center'}}>
              <Text style={{textAlign:'center',fontSize:getSize(19),marginTop:getSize(9)}}>个人中心</Text>
              <Button transparent style={{position:'absolute',right:getSize(10),paddingRight:0,paddingTop:0}}
                      onPress={()=>this._logOut()}>
                <Text style={{color:'#696969'}}>退出</Text>
              </Button>
            </View>
            <View style={{flexDirection:'row',flex:1}}>
              <View style={{alignItems:'center',marginTop:getSize(22)}}>
                <Image source={require('../images/header_img.png')} style={styles.header_img}/>
              </View>
              <View style={{justifyContent:'center',marginLeft:getSize(10)}}>
                <Text style={{color:'white',fontSize:getSize(15)}}>{nickName}</Text>
                <Text
                  style={{color:'white',marginTop:getSize(3),fontSize:getSize(15),fontWeight:'bold'}}>手机:{this.state.phone}</Text>
              </View>
            </View>
          </Image>
          <List style={{backgroundColor:'white'}}>
            <TouchableWithoutFeedback onPress={()=>this._toInformation()}>
              <ListItem style={{borderBottomWidth:getSize(10),borderBottomColor:'#F4F4F4'}} last>
                <Left>
                  <Text style={styles2.text}>基本资料</Text>
                </Left>
                <Body/>
                <Right>
                  <Icon name={'ios-arrow-forward'}/>
                </Right>
              </ListItem>
            </TouchableWithoutFeedback>
            <ListItem>
              <Left>
                <Text style={styles2.text}>联系电话</Text>
              </Left>
              <Right style={{flex:1}}>
                <Text note>{this.state.phone}</Text>
              </Right>
            </ListItem>
            <ListItem>
              <Left>
                <Text style={styles2.text}>联系地址</Text>
              </Left>
              <Right style={{flex:1}}>
                <Text note>{this.state.address}</Text>
              </Right>
            </ListItem>
            <TouchableWithoutFeedback onPress={()=>this.PageUtil.jumpPageWithComponent(Bank)}>
              <ListItem>
                <Left>
                  <Text style={styles2.text}>我的银行卡</Text>
                </Left>
                <Body />
                <Right>
                  <Icon name={'ios-arrow-forward'}/>
                </Right>
              </ListItem>
            </TouchableWithoutFeedback>
            <TouchableWithoutFeedback onPress={()=>this.PageUtil.jumpPageWithComponent(Services)}>
              <ListItem style={{borderBottomWidth:getSize(10),borderBottomColor:'#F4F4F4'}} last>
                <Left>
                  <Text style={styles2.text}>联系客服</Text>
                </Left>
                <Body />
                <Right>
                  <Icon name={'ios-arrow-forward'}/>
                </Right>
              </ListItem>
            </TouchableWithoutFeedback>
            <TouchableWithoutFeedback onPress={()=>this._updateVersion()}>
              <ListItem last>
                <Left>
                  <Text style={styles2.text}>当前版本</Text>
                </Left>
                <Body />
                <Right>
                  {this.state.versionView}
                </Right>
              </ListItem>
            </TouchableWithoutFeedback>
          </List>
        </Content>
        <VFooter/>
      </Container>
    );
  }
}
function select(store) {
  return {
    nickName: store.routesStore.updateNickName
  }
}
export default connect(select)(Person)
const styles = StyleSheet.create({
  personHead_img: {
    height: getSize(208),
    width: Dimensions.get('window').width,
    paddingTop: Platform.OS === 'ios' ? getSize(20) : 0,
  },
  settingIcon: {
    width: getSize(20),
    height: getSize(20),
    resizeMode: 'stretch'
  },
  header_img: {
    width: getSize(120),
    height: getSize(120),
    resizeMode: 'stretch',
  }
})
const styles2 = {
  text: {
    color: '#696969',
    fontSize: getSize(16)
  }
}